<template>
	<view class="">
		<u-collapse animation="true">
			<u-collapse-item
				ref="collapse"
				showAnimation
				@change="onCollapseChange"
				:index="`${index}-${sub.subid}`"
				v-for="(sub, index) in subjects"
				:title="sub.name"
				:key="'sub-' + sub.subid"
				modeType="列表"
			>
				<view class="loading" v-if="!sub.chapters">
					<u-loading mode="flower"></u-loading>
					<text>加载中...</text>
				</view>
				<view v-for="(chapter, index) in sub.chapters" v-if="chapter.counts>0" :key="chapter.chapterId" class="chapter">
					<view>
						<text class="text-ellipsis">{{ chapter.chapterName }}</text>
					</view>
					<view class="examIcon" @click="$emit('on-chapter-click', chapter)">
						<my-icon name="dati" style="color:#3E7DF1;font-size: 36upx;"></my-icon>
					</view>
					<!-- <image @click="$emit('on-chapter-click', chapter)" src="../static/icon/exam.png"></image> -->
				</view>
			</u-collapse-item>
		</u-collapse>
		<my-empty v-if="subjects.length === 0 && !loading"></my-empty>
	</view>
</template>

<script>
export default {
	props: ['getSubjectApi', 'getChapterApi', 'queBankId'],
	data() {
		return {
			subjects: [],
			loading: false
		};
	},
	watch: {
		queBankId() {
			this.getSubject();
		}
	},
	created() {
		this.getSubject();
	},
	methods: {
		getSubject() {
			//获取科目
			if (this.queBankId === null) return Promise.resolve();
			this.subjects = [];
			uni.showLoading({
				title: '获取章节中...'
			});
			this.loading = true;
			return new Promise((resolve, reject) => {
				this.request
					.get(`${this.getSubjectApi}${this.queBankId ? '/' + this.queBankId : ''}`)
					.then(res => {
						this.subjects = res;
						resolve();
					})
					.catch(reject)
					.finally(() => {
						this.loading = false;
						uni.hideLoading();
					});
			});
		},
		onCollapseChange(e) {
			let [index, subid] = e.index.split('-');
			if (this.subjects[index].chapters) return;
			this.request.get(`${this.getChapterApi}/${subid}`).then(res => {
				this.$set(this.subjects[index], 'chapters', res);
				this.$nextTick(function() {
					this.$refs.collapse[index].init();
				});
			});
		}
	}
};
</script>

<style lang="scss" scoped>
.chapter + .chapter {
	// border-top: 1px solid #ebebeb;
}
.u-collapse-item .chapter:last-child::before {
	display: none;
}
.examIcon>view{
	float: right;
	width: 40upx;
	margin-right: 30upx;
}
.chapter::before {
	content: '';
	position: absolute;
	left: 0;
	bottom: 0;
	display: block;
	width: 100%;
	height: 1upx;
	background: #ebebeb;
}
.chapter {
	display: flex;
	align-items: center;
	position: relative;
	view {
		flex: 1;
		text {
			max-width: 500upx;
		}
	}
	image {
		width: 34upx;
		height: 38upx;
		padding-right: 30upx;
	}
}
.loading {
	display: flex;
	justify-items: center;
	flex-direction: column;
	align-items: center;
	padding: 20upx 0;
	padding-right: 30upx;
}
</style>
